"use strict";
/* Controllers */
app.controller("summaryFlowController", ['$scope', '$location', '$rootScope', '$routeParams', 'summaryFlowService', function ($scope, $location, $rootScope, $routeParams, summaryFlowService) {

    var vm = $scope.vm = {};
    vm.p = {};
    vm.result = {};

    vm.p.topic = $routeParams.topic;
    vm.p.lspm = $routeParams.lspm;
    vm.p.slot = $routeParams.slot;

    /*
    0	platform,lspm_type,slot,is_ad,requesttype,disp_local1,disp_cate3
    7	platform,lspm_type,slot,is_ad
    31	platform,lspm_type
    **/
    vm.d = {spm:'31',slot:'7',cube:'0'};

    vm.p.topicId = '0'
    if (vm.p.topic != '0') {
        vm.p.topicId = vm.p.topic;
    }
    if (vm.p.lspm != '0') {
        vm.p.lspmType = vm.p.lspm;
    }
    if (vm.p.slot != '0') {
        vm.p.slot = vm.p.slot;
    }else {
        vm.p.slot = null;
    }

    var datePicker = $('.date');
    datePicker.datetimepicker({
        locale: 'zh-cn',
        format: 'YYYY-MM-DD'
    });
    datePicker.on('dp.hide', function (e) {
        var currentInput = $(e.currentTarget).find('input');
        var eName = currentInput.attr('name');
        var p = $scope.vm.p;
        p[eName] = currentInput.val();
        $scope.$apply()
    });

    // $("#startDt").on("dp.change", function (e) {
    //     $('#endDt').data("DateTimePicker").minDate(e.date);
    // });
    // $("#endDt").on("dp.change", function (e) {
    //     $('#startDt').data("DateTimePicker").maxDate(e.date);
    // });

    if ($scope.vm.p.dt == '' || $scope.vm.p.dt == '0' || typeof ($scope.vm.p.dt) == 'undefined') {
        $scope.vm.p.dt = new Date(new Date().getTime() - 86400000*2).format('yyyy-MM-dd');
    }
    if ($scope.vm.p.dt2 == '' || $scope.vm.p.dt2 == '0' || typeof ($scope.vm.p.dt2) == 'undefined') {
        $scope.vm.p.dt2 = new Date(new Date().getTime() - 86400000).format('yyyy-MM-dd');
    }


    var errorFn = function (result) {
        alert(result);
    };
    $scope.queryReport = function () {
        $scope.listSummaryReport();
    };
    $scope.listSummaryReport = function () {
        $("#refreshTable").addClass('disabled');
        $("#list_table").bootstrapTable('showLoading')
        var vm = $scope.vm;
        vm.result.ms = "...";


        var params = {};
        for(let i in vm.p){
            params[i] = vm.p[i];
        }
        // 默认值处理
        if(vm.p.platform=='0' || vm.p.platform=='all') {
            params.platform = null;
        }
        if(vm.p.isAd=='0' || vm.p.isAd=='all') {
            params.isAd = null;
        }
        if(vm.p.lspmType=='0' || vm.p.lspmType=='all') {
            params.lspmType = null;
        }
        if(vm.p.slot=='0' || vm.p.slot=='all') {
            params.slot = null;
        }

        var procFn = function (response) {
            vm.result.ms = response.ms;
            var data = response.data;
            $('#list_table').bootstrapTable('hideLoading');
            $("#refreshTable").removeClass('disabled');
            if (data == null) return;
            $("#list_table").bootstrapTable('showAllColumns')
            if (vm.p.topicId == '31') {
                $("#list_table").bootstrapTable('hideColumn', 'slot');
                $("#list_table").bootstrapTable('hideColumn', 'isAd');
                $("#list_table").bootstrapTable('hideColumn', 'requesttype');
                $("#list_table").bootstrapTable('hideColumn', 'dispLocal1Cn');
                $("#list_table").bootstrapTable('hideColumn', 'dispCate3Cn');


                $("#list_table").bootstrapTable('hideColumn', 'searchCnt');
                $("#list_table").bootstrapTable('hideColumn', 'searchUv');

                $("#list_table").bootstrapTable('hideColumn', 'clickCnt');
                $("#list_table").bootstrapTable('hideColumn', 'imReadCnt');
                $("#list_table").bootstrapTable('hideColumn', 'imReplyCnt');
                $("#list_table").bootstrapTable('hideColumn', 'telConnCnt');
                $("#list_table").bootstrapTable('hideColumn', 'dispLocal1Cn');
                $("#list_table").bootstrapTable('hideColumn', 'dispCate3Cn');
            } else if (vm.p.topicId == '7') {
                $("#list_table").bootstrapTable('hideColumn', 'biz');
                $("#list_table").bootstrapTable('hideColumn', 'platform');

                $("#list_table").bootstrapTable('hideColumn', 'requesttype');
                $("#list_table").bootstrapTable('hideColumn', 'dispLocal1Cn');
                $("#list_table").bootstrapTable('hideColumn', 'dispCate3Cn');

                $("#list_table").bootstrapTable('hideColumn', 'searchCnt');
                $("#list_table").bootstrapTable('hideColumn', 'searchUv');
                $("#list_table").bootstrapTable('hideColumn', 'clickCnt');
                $("#list_table").bootstrapTable('hideColumn', 'imReadCnt');
                $("#list_table").bootstrapTable('hideColumn', 'imReplyCnt');
                $("#list_table").bootstrapTable('hideColumn', 'telConnCnt');
            } else if (vm.p.topicId == '0') {
                $("#list_table").bootstrapTable('hideColumn', 'biz');
                $("#list_table").bootstrapTable('hideColumn', 'platform');
            }
            $("#list_table").bootstrapTable('hideColumn', 'topicId');
            $("#list_table").bootstrapTable('hideColumn', 'deliveryUv');
            $("#list_table").bootstrapTable('hideColumn', 'imUv');
            $("#list_table").bootstrapTable('hideColumn', 'telUv');
            $("#list_table").bootstrapTable('hideColumn', 'telConnUv');
            $("#list_table").bootstrapTable('hideColumn', 'omsCost');
            // 串联数据隐藏
            $("#list_table").bootstrapTable('hideColumn', 'expCnt1');
            $("#list_table").bootstrapTable('hideColumn', 'clickCnt1');
            $("#list_table").bootstrapTable('hideColumn', 'deliveryCnt1');
            $("#list_table").bootstrapTable('hideColumn', 'imCnt1');
            $("#list_table").bootstrapTable('hideColumn', 'telCnt1');
//            $("#list_table").bootstrapTable('hideColumn', 'ctr3');
//            $("#list_table").bootstrapTable('hideColumn', 'cvr3');
//            $("#list_table").bootstrapTable('hideColumn', 'imr3');
//            $("#list_table").bootstrapTable('hideColumn', 'telr3');

            vm.result.data = data;
            $('#list_table').bootstrapTable('load', data);

        };
        summaryFlowService.listSummaryFlow(params, procFn, errorFn);
    };

    $scope.initializeController = function () {
        vm.result.ms = '';
        var $resultTable = $('#list_table');
        $resultTable.bootstrapTable({
            exportDataType: 'all',
            exportTypes: ['excel', 'json', 'xml', 'csv', 'txt'],
            pageList: [30, 50, 100, 300, 500, 1000, 3000], pageSize: 30
        });
        $scope.listSummaryReport();
    };

    $scope.initializeController();

    $scope.toggleInteval = function (topicId) {
        var vm = $scope.vm;
        vm.p.topicId = topicId;
        $location.path('/star/report/summary_flow/' + vm.p.topicId + '/0/0').replace();
        //        $scope.queryReport()

    }

    $scope.toMetricChart = function (field, index) {
        let $table = $('#list_table')
        let tableData = $table.bootstrapTable('getData');
        let curRow = tableData[index]

        var dom = document.getElementById('metric_chart');
        var myChart = echarts.init(dom);
        myChart.showLoading()

        var params = {};
        params.field = field
        params.topicId = curRow.topicId
        params.biz = curRow.biz
        params.platform = curRow.platform
        params.slot = curRow.slot
        params.requesttype = curRow.requesttype

        params.dispLocal1 = curRow.dispLocal1
        params.dispCate3 = curRow.dispCate3

        var procFn = function (response) {
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            let modalTitle = '趋势图'

            $scope.vm.modalTitle = modalTitle
            initChart(myChart, data.chartData, field)
            myChart.hideLoading()
        };
        summaryFlowService.getSummaryFlowChart(params, procFn, errorFn);

        $('#myModal').modal('show')
    }

    function initChart(myChart, data, title) {

        var dateList = data.map(function (item) {
            return item[0];
        });
        var valueList = data.map(function (item) {
            return item[1];
        });
        // var dom = document.getElementById("container");

        window.onresize = function () {
            myChart.resize();
        };
        var option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'cross' }
            },
            legend: {
            },
            dataZoom: [{}],
            xAxis: {
                type: 'category',
                data: dateList
            },
            yAxis: [
                {
                    name: '指标值',
                    type: 'value'
                }
            ],
            series: [
                {
                    name: title,
                    yAxisIndex: 0,
                    data: valueList,
                    type: 'line',
                    smooth: true
                }
            ]
        };
        window.onresize = function () {
            myChart.resize();
        };
        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }
    }

}]);

/* Services */
app.service('summaryFlowService', ['ajaxService', function (ajaxService) {

    this.listSummaryFlow = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/report/listSummaryFlow.do", successFunction, errorFunction);
    };

    this.getSummaryFlowChart = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/report/getSummaryFlowChart.do", successFunction, errorFunction);
    };

}]);

function summaryFlowFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        numberFmt(value),
        '</a>  ',
    ].join('')
}

function summaryFlowRatioFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
    ].join('')
}

//
function ctr3Formatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.clickCnt1, '/', row.expCnt1, ')'
    ].join('')
}
function cvr3Formatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.deliveryCnt1, '/', row.expCnt1, ')'
    ].join('')
}

function imr3Formatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.imCnt1, '/', row.expCnt1, ')'
    ].join('')
}

function telr3Formatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.telCnt1, '/', row.expCnt1, ')'
    ].join('')
}




function platformFormat(value, row, index, field) {
    if (value == 1) {
        return 'pc'
    } else if (value == 2) {
        return 'm'
    } else if (value == 3) {
        return 'app'
    } else if (value == 4) {
        return '小程序'
    } else if (value == 5) {
        return 'wap'
    } else {
        return '-'
    }
}

function lspmTypeFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var value2 = value;
    if(value==='-') {
        value2 = '站内流量';
    }
    return [
        '<a href="#/star/report/summary_flow/7/', value, '/0" target="_blank"><u>', value2, '</u></a>'
    ].join('');
}

function slotFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var cn = '';
    if(row.slotCn!='' &&  row.slotCn!='-') {
        cn = [' (', row.slotCn, ')'].join('');
    }
    return [
        '<a href="#/star/report/summary_flow/0/0/', value, '" target="_blank"><u>', value, '</u></a>',
        cn
    ].join('');
}


function platformFormat(value, row, index, field) {
    if (value == 1) {
        return 'PC'
    } else if (value == 2) {
        return 'M'
    } else if (value == 3) {
        return 'APP'
    } else if (value == -999999) {
        return '其他'
    } else {
        return '-'
    }
}

function isAdFormat(value, row, index, field) {
    if (value == 0) {
        return '否'
    } else if (value == 1) {
        return '是'
    } else {
        return '-'
    }
}


function dispLocal1NameFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var cn = '';
    if(row.dispLocal1!='' &&  row.dispLocal1!='-') {
        cn = [' (', row.dispLocal1, ')'].join('');
    }
    return value + cn
}

function dispCate3NameFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var cn = '';
    if(row.dispCate3!='' &&  row.dispCate3!='-') {
        cn = [' (', row.dispCate3, ')'].join('');
    }
    return value + cn
}

function requesttypeFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    switch(value) {
    case 'pt':
        return '普通（' + value+'）';
    case 'jp':
        return '精品（' + value+'）';
    case 'jz':
        return '精准（' + value+'）';
    case 'yx':
        return '优选（' + value+'）';
   default:
        break;
    }
    return value;
}



